<?php

namespace App\Service\OpenShop\Import\HistoryOrder;

use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Remote\Orm\OrmShopRemote;
use App\Service\OpenShop\Feishu\MissionTemplateService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\OpenShop\UserContractService;
use Illuminate\Support\Facades\Redis;

class HistoryOrderParam
{
    public static bool $importOrderMode = false; // 订单导入模式
    public static ?object $forceCurrentUser = null; // 强制-当前处理人

    public int   $shopCode;
    private bool $fakeShopCode = false;

    public int     $stepStatus;
    private int    $stepStatusSort;
    public string $stepStatusText;

    public string $name;
    public ?string $identityNo;
    public string $phone;

    // 门店选址范围
    public string $siteMerge;
    public string $siteAddress;
    public int    $siteProvinceCode = 0;
    public int    $siteCityCode     = 0;
    public int    $siteDistrictCode = 0;

    // 是否自带选址
    public int     $isSelfWithAddress;
    public string $isSelfWithAddressText;

    // 签约类型
    public int      $contractType;
    private ?string $contractTypeText;

    // 加盟政策模板
    public int     $contractTemplateId;
    public string $contractTemplateText;

    private ?int $signDate; // 用户签约日期
    public int   $signTime; // 用户签约日期
    private ?int $contractStartDate; // 合同开始时间
    public int   $contractStartTime; // 合同开始时间
    private ?int $startBusinessDate; // 预计开业时间
    public int   $startBusinessTime; // 预计开业时间

    public ?int $designPrice; // 设计费
    public ?int $merchantPrice; // 商户通
    public ?int $overDesignPrice; // 超标设计费

    public ?int $equipmentPrice; // 设备报价
    public ?int $decoratePrice; // 软装报价

    // 顾问
    public ?string $managerSalesName; // 招商顾问
    public ?array  $managerSales;

    public ?string $managerDevelopName; // 开发顾问
    public ?array  $managerDevelop;

    public ?string $managerDesignName; // 设计顾问
    public ?array  $managerDesign;

    public ?string $managerPrepareName; // 筹备顾问
    public ?array  $managerPrepare;

    public ?string $managerOperateName; // 营运负责人，督导
    public ?array  $managerOperate;

    public ?string $managerProvinceName; // 省总
    public ?array  $managerProvince; // 省总

    public ?string $shopTag; // 门店标签

    public int    $row;
    private string $errMsg = '';
    private string $noticeMsg = '';

    // 流程中创建的属性
    public string $orderNo;

    private bool $debug = false;

    public function init(array $data, int $row)
    {
        $this->row = $row;

        if ($row == 1) {

            // 检查列名
            $this->checkColumn($data);
            return $this;
        }

        foreach ($data as $k => &$v) {
            $v = is_string($v) ? trim($v) : $v;

            if ($v === null) {
                if (in_array($k, [0, 10, 11, 12, 13, 14, 15, 16, 17])) {

                    // int
                    $v = 0;
                } else {

                    // string
                    $v = '';
                }
            }
        }

        dump($data);

        list(
            $this->shopCode,
            $this->stepStatusText,
            $this->name,
            $this->identityNo,
            $this->phone,
            $this->siteMerge,
            $this->siteAddress,
            $this->isSelfWithAddressText,
            $this->contractTypeText,
            $this->contractTemplateText,
            $this->signDate,
            $this->contractStartDate,
            $this->startBusinessDate,
            $this->designPrice,
            $this->merchantPrice,
            $this->overDesignPrice,
            $this->equipmentPrice,
            $this->decoratePrice,
            $this->managerSalesName,
            $this->managerDevelopName,
            $this->managerDesignName,
            $this->managerOperateName,
            $this->shopTag,
            ) = $data;


        $this->identityNo = strtoupper($this->identityNo);
        $this->name       = str_replace(" \t\n\r\0\x0B", '', $this->name);
        $this->identityNo = (string)$this->identityNo;

        // 强制修改，设备模块待支付
        if ($this->stepStatusText == MissionTemplateEnum::STEP_STATUS_TEXT[MissionTemplateEnum::STEP_STATUS_16]) {
            $this->stepStatusText = MissionTemplateEnum::STEP_STATUS_TEXT[MissionTemplateEnum::STEP_STATUS_15];
        }

        if ($this->stepStatusText == '指派开发经理') {
            $this->stepStatusText = '开发待指派';
        }

        if (config('app.env') == 'dev') {
            $this->shopCode = $this->fakerShopCode();
        }

        if (config('app.env') == 'qa' || config('app.env') == 'dev') {
            if ($this->shopCode == -1) {
                $this->shopCode = $this->fakerShopCode();
            }
        }

        dump("shopCode: {$this->shopCode}");

        // TODO DEBUG
//        $this->shopCode = 1;
//        $this->phone = '13917836275';
//        $this->stepStatusText = MissionTemplateEnum::STEP_STATUS_TEXT[MissionTemplateEnum::STEP_STATUS_15];
//        $this->siteMerge = '陕西省';
//        $this->managerSalesName = 'cja';
//        $this->managerDevelopName = 'cja';
//        $this->managerDesignName = 'cja';
//        $this->managerOperateName = 'cja';

        return $this;
    }

    private function fakerShopCode(): int
    {
        $this->fakeShopCode = true;

        if (!Redis::get('fake_shop_code')) {
            $shopCode = ((int)OpenShopSignOrderModel::query()->orderByDesc('provideShopCode')
                                                    ->value('provideShopCode'));
            Redis::set('fake_shop_code', $shopCode);
        }

        return Redis::incr('fake_shop_code', 1);
    }

    /**
     * 检查列名
     * @param array $data
     * @return void
     */
    private function checkColumn(array $data): void
    {
        $formColumn = [
            "门店编号",
            "所属开店阶段",
            "姓名",
            "身份证号",
            "手机号",
            "门店选址范围",
            "门店详细地址",
            "是否有自带选址",
            "签约类型",
            "加盟政策",
            "用户签约日期",
            "合同开始日期",
            "预计开业时间",
            "设计费",
            "商户通",
            "超标设计费",
            "设备报价",
            "软装报价",
            "招商顾问",
            "开发顾问",
            "设计顾问",
            "营运顾问",
            "店数",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $data[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }

        if ($this->errMsg) {
            SendFs::newRobot(SendFs::ROBOT_INTERNAL)->setTitleContent("导入历史开店订单模板异常", $this->errMsg)->send();
            dump($this->errMsg);
            die;
        }
    }

    public function prepareParam(int $import = 0): self
    {
        // 列名不校验
        if ($this->row == 1) {
            return $this;
        }

        try {

            if ($import == 0) {

                // 常规步骤
                $this->checkContractTemplateText();
                $this->checkShopCode();
                $this->checkStepStatus();
                $this->checkUserInfo();
                $this->checkSiteMerge();
                $this->checkIsSelfWithAddressText();
                $this->checkContractTypeText();
                $this->checkDate();
                $this->checkManager();
            } else {

                // 导入步骤
//                $this->checkContractTemplateText();
//                $this->checkShopCode();
                $this->checkStepStatus();
//                $this->checkUserInfo();
                $this->checkSiteMerge();
//                $this->checkIsSelfWithAddressText();
//                $this->checkContractTypeText();
//                $this->checkDate();
                $this->checkManager();
            }

        } catch (CustomHttpResponseException $e) {
            $this->errMsg .= "第{$this->row}行，" . ($e->getResponse()->original['msg'] ?? '') . PHP_EOL;
        } catch (\Exception $e) {
            $this->errMsg .= "第{$this->row}行，" . $e->getMessage() . PHP_EOL;
        }

        return $this;
    }

    public function getErrMsg(): string
    {
        return $this->errMsg;
    }

    public function getNoticeMsg(): string
    {
        return $this->noticeMsg;
    }

    private function dumpFunctionName(string $functionName)
    {
        if ($this->debug) {
            dump($functionName);
        }
    }

    private function checkShopCode(): void
    {
        try {
            UserContractService::checkProvideShopCode($this->shopCode, $this->contractTemplateId);
        } catch (CustomHttpResponseException $e) {
            $code = $e->getResponse()->original['code'] ?? 0;

            // shopCode rms重复仅提示，不做拦截
            if ($code == ErrCode::CODE_ERR_SHOP_CODE) {
                $this->noticeMsg .= "第{$this->row}行，" . ($e->getResponse()->original['msg'] ?? '') . "shopCode={$this->shopCode}";
                return;
            }

            throw new \Exception("错误的门店编号:{$this->shopCode};" . ($e->getResponse()->original['msg'] ?? ''));
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkStepStatus(): void
    {
        $this->stepStatus = array_flip(MissionTemplateEnum::STEP_STATUS_TEXT)[$this->stepStatusText] ?? -1;
        if ($this->stepStatus == -1) {
            throw new \Exception("不存在的所属开店阶段:{$this->stepStatusText}");
        }

        // 针对完成订单的特殊处理
        if ($this->stepStatus == MissionTemplateEnum::STEP_STATUS_999) {
            $this->stepStatusSort = 999;
        } else {
            $this->stepStatusSort = MissionTemplateService::getSortByStepStatus($this->stepStatus);
        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkUserInfo(): void
    {
        if (!$this->name) {
            throw new \Exception("姓名不能为空");
        }

        if (!$this->phone) {
            throw new \Exception("手机号不能为空");
        }

        if (!preg_match("/^1\d{10}$/", $this->phone)) {
            throw new \Exception("手机号格式错误");
        }

//        if (!$this->identityNo) {
//            throw new \Exception("身份证号不能为空");
//        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkSiteMerge(): void
    {
        $siteNames      = explode('/', $this->siteMerge);
        $countSiteNames = count($siteNames);

        if ($countSiteNames != 3 && $countSiteNames != 2 && $countSiteNames != 1) {
            throw new \Exception("门店选址范围错误，请用/隔开省市区");
        }

        $siteData = (new RmsShopApi())->getAreaCodeByArea($siteNames)['data'];

        collect($siteData)->each(function ($item) {
            if ($item['level'] == 1) {
                $this->siteProvinceCode = $item['code'];
                return;
            }

            if ($item['level'] == 2) {
                $this->siteCityCode = $item['code'];
                return;
            }

            if ($item['level'] == 3) {
                $this->siteDistrictCode = $item['code'];
                return;
            }
        });

        if (!$this->siteProvinceCode) {
            throw new \Exception($siteNames[0] . '：无法找到对应地区code');
        }
        if ($countSiteNames == 2 && !$this->siteCityCode) {
            throw new \Exception($siteNames[1] . '：无法找到对应地区code');
        }

        if ($countSiteNames == 3 && !$this->siteDistrictCode) {
            throw new \Exception($siteNames[2] . '：无法找到对应地区code');
        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkIsSelfWithAddressText(): void
    {
        if ($this->isSelfWithAddressText == '是') {
            $this->isSelfWithAddress = 1;
        } else {
            $this->isSelfWithAddress = 0;
        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkContractTypeText(): void
    {
        if ($this->contractTypeText == '新店加盟') {
            $this->contractType = 1;

            $this->dumpFunctionName(__FUNCTION__);
            return;
        }

        if ($this->contractTypeText == '老店裂变') {
            $this->contractType = 2;

            $this->dumpFunctionName(__FUNCTION__);
            return;
        }

        throw new \Exception("签约类型填写错误");
    }

    private function checkContractTemplateText(): void
    {
        $template = OpenShopContractTemplateModel::query()->where('templateName', $this->contractTemplateText)->first();
        if (!$template) {
            throw new \Exception("不存在的加盟政策");
        }

        $this->contractTemplateId = $template->id;

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkDate(): void
    {
        $this->signTime          = $this->convertExcelDate($this->signDate);
        $this->contractStartTime = $this->convertExcelDate($this->contractStartDate);
        $this->startBusinessTime = $this->convertExcelDate($this->startBusinessDate);

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function convertExcelDate(?int $excelDate): int
    {
        $excelInitDate = 25569; // 1970的值

        if ($excelDate) {
            $excelTime = strtotime(date('Ymd', ($excelDate - $excelInitDate) * 86400 + 8 * 3600));
        } else {
            $excelTime = 0;
        }

        return (int)$excelTime;
    }

    private function checkPrice(): void
    {
//        if ($this->stepStatusSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_14)) {
//            if ($this->designPrice <= 0 || $this->merchantPrice <= 0) {
//                throw new \Exception("当前阶段，设计费、商户通不能为空");
//            }
//        }
//
//        if ($this->stepStatus >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_16)) {
//            if ($this->equipmentPrice <= 0) {
//                throw new \Exception("当前阶段，设备报价不能为空");
//            }
//        }
//
//        if ($this->stepStatus >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_17)) {
//            if ($this->decoratePrice <= 0) {
//                throw new \Exception("当前阶段，软装报价不能为空");
//            }
//        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkManager(): void
    {
        // 根据开店组织，获取省总、筹备负责人
        $manager = OrganizationManageService::getOrganizationInfoByProvinceCodeCode($this->siteProvinceCode);
        if (!$manager) {
            throw new \Exception($this->siteMerge . ";获取开店组织失败;provinceCode:{$this->siteProvinceCode}");
        }

        $managerLists              = collect(RmsUserService::getRmsUserInfoByUserIds([
                $manager['preparationUid'],
                $manager['operationUid']
            ])['data'] ?? [])
            ->keyBy('id');
        $this->managerPrepareName  = $managerLists[$manager['preparationUid']]['username'] ?? '';
        $this->managerProvinceName = $managerLists[$manager['operationUid']]['username'] ?? '';
        $this->managerPrepare      = $managerLists[$manager['preparationUid']] ?? [];
        $this->managerProvince     = $managerLists[$manager['operationUid']] ?? [];

        if (!$this->managerPrepareName) {
            throw new \Exception($this->siteMerge . ";获取筹备顾问失败;provinceCode:{$this->siteProvinceCode} userId:{$manager['preparationUid']}");
        }

        if (!$this->managerProvinceName) {
            throw new \Exception($this->siteMerge . ";获取营运顾问失败;provinceCode:{$this->siteProvinceCode} userId:{$manager['operationUid']}");
        }

        // 从excel中的负责人名，获取用户信息
        $usernames = [
            $this->managerSalesName,
            $this->managerDevelopName,
            $this->managerDesignName,
            $this->managerOperateName,
        ];

        $arr = collect((new RmsUserApi())->getInfoByUsernames($usernames)['data'])->toArray();

        $this->managerSales   = $arr[0] ?? [];
        $this->managerDevelop = $arr[1] ?? [];
        $this->managerDesign  = $arr[2] ?? [];
        $this->managerOperate = $arr[3] ?? [];

        // 从后往前的顺序写
        if ($this->stepStatusSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_12)) {

            if ($this->managerOperateName && !$this->managerOperate) {
                throw new \Exception("营运顾问『{$this->managerOperateName}』运营后台不存在");
            }

            if (!$this->managerOperate) {
                throw new \Exception("当前阶段『{$this->stepStatusText}』，营运顾问不能为空");
            }
        }

        if ($this->stepStatusSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_13)) {

            if ($this->managerDesignName && !$this->managerDesign) {
                throw new \Exception("设计顾问『{$this->managerDesignName}』运营后台不存在");
            }

            if (!$this->managerDesign) {
                throw new \Exception("当前阶段『{$this->stepStatusText}』，设计顾问不能为空");
            }
        }

        if ($this->stepStatusSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_6)) {

            if ($this->managerPrepareName && !$this->managerPrepare) {
                throw new \Exception("筹备顾问『{$this->managerPrepareName}』运营后台不存在");
            }

            if (!$this->managerPrepare) {
                throw new \Exception("当前阶段『{$this->stepStatusText}』，筹备顾问不能为空");
            }
        }

        if ($this->stepStatusSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_4)) {

            if ($this->managerDevelopName && !$this->managerDevelop) {
                throw new \Exception("开发顾问『{$this->managerDevelopName}』运营后台不存在");
            }

            if (!$this->managerDevelop) {
                throw new \Exception("当前阶段『{$this->stepStatusText}』，开发顾问不能为空");
            }
        }

        if ($this->managerSalesName && !$this->managerSales) {
            throw new \Exception("招商顾问『{$this->managerSalesName}』运营后台不存在");
        }

        if (!$this->managerSales) {
            throw new \Exception("招商顾问不能为空");
        }

        $this->dumpFunctionName(__FUNCTION__);
    }

    private function checkOrmBuild(): void
    {
        if ($this->stepStatusSort >= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_15)) {
            $checkBuild = OrmShopRemote::getStoreByShopCode($this->shopCode);
            if ($checkBuild['code'] != 0) {

                $this->noticeMsg .= "第{$this->row}行，" . "shopCode={$this->shopCode}未建档，强制执行将自动建档";

//                // 开发环境就直接建出来
//                if (config('app.env') == 'dev' || $this->fakeShopCode) {
//                    $name        = $this->name . $this->shopCode;
//                    $shopName    = $name . '的店';
//                    $createStore = OrmShopRemote::createStore($shopName, $this->phone, $name, $this->shopCode,
//                        $this->siteDistrictCode);
//                } else {
//                    throw new \Exception("订货未建档");
//                }
            }
        }

        $this->dumpFunctionName(__FUNCTION__);
    }
}
